<template>
  <div class="form-editor"
    style="padding: 20px; background: #f5f7fa; min-height: 100vh; width: 100%; display: flex; gap: 20px;">

    <!-- 左侧导航 -->
    <div class="category-nav"
      style="width: 200px; background: white; border-radius: 8px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); overflow-y: auto;">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
        <span style="font-size: 14px; color: #666;">表单类别列表</span>
        <el-input v-model="searchCategory" placeholder="请输入..." size="small" style="width: 100%;" />
      </div>

      <el-menu :default-active="activeForm" @select="handleFormChange" style="border-right: none;">
        <el-menu-item index="0">随访表单</el-menu-item>
        <el-menu-item index="1">高血压随访表</el-menu-item>
        <el-menu-item index="2">糖尿病随访表</el-menu-item>
        <el-menu-item index="3">高血脂随访表</el-menu-item>
      </el-menu>
    </div>

    <!-- 右侧主内容区 -->
    <div class="main-content"
      style="flex: 1; background: white; border-radius: 8px; padding: 30px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); overflow-y: auto;">

      <!-- 顶部信息 -->
      <div
        style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-bottom: 20px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
          <h3 style="margin: 0; font-size: 18px; color: #333;">{{ currentForm?.FollowupName }}</h3>
          <div>
            <el-button type="primary" size="small" @click="handlePublish">发布</el-button>
            <el-button size="small" @click="handleEdit">详情</el-button>
            <el-button type="danger" size="small" @click="handleDelete">删除</el-button>
          </div>
        </div>

        <div style="display: flex; gap: 50px; font-size: 14px; color: #666;">
          <span>创建时间：{{ currentForm?.DateTime?.toLocaleString() }}</span>
          <span>更新时间：{{ currentForm?.GetDateTime?.toLocaleString() }}</span>
          <span>创建人员：{{ currentForm?.FormCategorypeople }}</span>
          <span>表单状态：{{ currentForm?.IsFollowing ? '已发布' : '未发布' }}</span>
        </div>
      </div>

      <!-- 中间区域 -->
      <div style="display: flex; gap: 20px;">

        <!-- 左侧元素选择区 -->
        <div class="element-selector"
          style="width: 300px; background: white; border-radius: 8px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">

          <!-- 元素类型切换 -->
          <div style="display: flex; gap: 10px; margin-bottom: 16px;">
            <el-tag :type="activeElementType === '元素类型' ? 'primary' : 'info'" effect="plain" size="small"
              @click="switchElementType('元素类型')" style="cursor: pointer;">
              元素类型
            </el-tag>
            <el-tag :type="activeElementType === '体征元素' ? 'primary' : 'info'" effect="plain" size="small"
              @click="switchElementType('体征元素')" style="cursor: pointer;">
              体征元素
            </el-tag>
          </div>

          <!-- 搜索框 -->
          <el-input v-model="searchElement" placeholder="请输入元素名称查找" size="small"
            style="margin-bottom: 16px;" />

          <!-- 元素列表 -->
          <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
            <div 
              v-for="item in filteredElements" 
              :key="item.id"
              style="background: #f0f9ff; padding: 10px; border-radius: 4px; cursor: pointer; text-align: center; font-size: 14px; color: #1a5276; border: 1px solid #b3d9ff;"
              @click="insertField(item.name)"
            >
              <el-icon><DocumentAdd /></el-icon> {{ item.name }}
            </div>
          </div>

        </div>

        <!-- 右侧富文本编辑区 -->
        <div class="rich-text-editor"
          style="flex: 1; background: white; border-radius: 8px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">

          <!-- 富文本工具栏 -->
          <div style="border: 1px solid #ccc; border-radius: 4px;">
            <Toolbar 
              style="border-bottom: 1px solid #ccc" 
              :editor="editorRef" 
              :defaultConfig="toolbarConfig" 
              :mode="'default'" 
            />
            <Editor 
              style="height: 500px;" 
              v-model="valueHtml" 
              :defaultConfig="editorConfig" 
              :mode="'default'" 
              @onCreated="handleCreated"
              @onChange="handleEditorChange"
            />
          </div>

          <!-- 底部按钮 -->
          <div style="display: flex; justify-content: flex-end; margin-top: 20px;">
            <el-button size="small" @click="handleSave">保存</el-button>
            <el-button type="primary" size="small" @click="handlePublish">发布</el-button>
          </div>

        </div>

      </div>

    </div>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="dialogVisible" title="表单详情" width="500px">
      <el-form :model="formData" label-width="100px">
        <el-form-item label="表单名称:">
          <el-input v-model="formData.FollowupName" disabled />
        </el-form-item>
        <el-form-item label="创建人员:">
          <el-input v-model="formData.FormCategorypeople" disabled />
        </el-form-item>
        <el-form-item label="表单状态:">
          <el-switch v-model="formData.IsFollowing" active-text="已发布" inactive-text="未发布" disabled />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, shallowRef, onBeforeUnmount } from 'vue'
import { DocumentAdd } from '@element-plus/icons-vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// ===== 表单与导航 =====
const activeForm = ref('2')
const searchCategory = ref('')
const activeElementType = ref('体征元素')
const searchElement = ref('')

// 固定元素
const fixedElements = [
  { id: 1, name: '舒张压', type: '体征元素' },
  { id: 2, name: '收缩压', type: '体征元素' },
  { id: 3, name: '心率', type: '体征元素' },
  { id: 4, name: '体温', type: '体征元素' },
  { id: 5, name: '脉搏', type: '体征元素' },
  { id: 6, name: '呼吸', type: '体征元素' },
  { id: 7, name: '身高', type: '体征元素' },
  { id: 8, name: '体重', type: '体征元素' },
  { id: 9, name: '体质指数', type: '体征元素' },
  { id: 10, name: '血氧饱和度', type: '体征元素' }
]

const filteredElements = computed(() => {
  let list = fixedElements.filter(item => item.type === activeElementType.value)
  if (searchElement.value) {
    list = list.filter(item => item.name.includes(searchElement.value))
  }
  return list
})

const switchElementType = (type) => {
  activeElementType.value = type
}

// 模拟表单数据
const forms = ref([
  {
    FollowupId: 1,
    FormCategoryId: 1,
    FollowupName: '高血压随访表',
    DateTime: new Date('2019-10-01'),
    GetDateTime: new Date('2023-10-20'),
    FormCategorypeople: '张三',
    IsFollowing: false
  },
  {
    FollowupId: 2,
    FormCategoryId: 2,
    FollowupName: '糖尿病随访表',
    DateTime: new Date('2020-01-01'),
    GetDateTime: new Date('2023-10-20'),
    FormCategorypeople: '李四',
    IsFollowing: true
  },
  {
    FollowupId: 3,
    FormCategoryId: 3,
    FollowupName: '高血脂随访表',
    DateTime: new Date('2021-03-01'),
    GetDateTime: new Date('2023-10-20'),
    FormCategorypeople: '王五',
    IsFollowing: false
  }
])

const currentForm = computed(() => {
  return forms.value.find(f => f.FormCategoryId == parseInt(activeForm.value)) || null
})

const handleFormChange = (index) => {
  activeForm.value = index
}

// ===== 编辑弹窗 =====
const dialogVisible = ref(false)
const formData = ref({
  FollowupId: null,
  FollowupName: '',
  FormCategorypeople: '',
  IsFollowing: false
})

const handleEdit = () => {
  if (!currentForm.value) {
    ElMessage.warning('请选择表单')
    return
  }
  formData.value = { ...currentForm.value }
  dialogVisible.value = true
}

// ===== 富文本编辑器 =====
const editorRef = shallowRef()
const valueHtml = ref('<p>请在此编辑表单内容...</p>')

const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...'
}

const handleCreated = (editor) => {
  editorRef.value = editor
}

const handleEditorChange = (editor) => {
  valueHtml.value = editor.getHtml()
}

onBeforeUnmount(() => {
  if (editorRef.value) editorRef.value.destroy()
})

// 插入字段
const insertField = (fieldName) => {
  if (!editorRef.value) {
    ElMessage.warning('编辑器未就绪')
    return
  }
  const html = `<span class="form-field" data-field="${fieldName}" contenteditable="false">[${fieldName}]</span>`
  editorRef.value.insertHtml(html)
}

// ===== 操作方法 =====
const handleSave = () => {
  if (!currentForm.value) {
    ElMessage.warning('请先选择一个表单')
    return
  }

  const payload = {
    FollowupId: currentForm.value.FollowupId,
    TextfieldName: valueHtml.value   // ✅ 关键：和后端模型字段名完全一致！
  }

  axios.post("http://localhost:5203/api/Managment/AddTextfield", payload)
    .then(res => {
      if (res.data.code === 200) {
        ElMessage.success('保存成功')
      } else {
        ElMessage.error(res.data.message || '保存失败')
      }
    })
   
}

const handlePublish = () => {
  if (currentForm.value) {
    const index = forms.value.findIndex(f => f.FollowupId === currentForm.value.FollowupId)
    if (index !== -1) {
      forms.value[index].IsFollowing = true
      forms.value[index].GetDateTime = new Date()
    }
    ElMessage.success('发布成功')
  }
}

const handleDelete = () => {
  ElMessage.warning('删除表单？')
}
</script>

<style scoped>
.form-field {
  display: inline-block;
  background: #e3f2fd;
  border: 1px solid #2196f3;
  border-radius: 4px;
  padding: 0 6px;
  margin: 0 2px;
  color: #1976d2;
  font-size: 14px;
  line-height: 1.8;
  cursor: default;
  user-select: none;
}
</style>